import { LoadingOutlined, UploadOutlined } from '@ant-design/icons';
import { ActionType } from '@ant-design/pro-components';
import { Button, Divider, Modal, Progress, Spin, Upload, message } from 'antd';
import ExportJsonExcel from 'js-export-excel';
import download from '@/utils/downVideo';
import { read, utils } from 'xlsx';
import React, { useState } from 'react'
import { import_patient_list } from '@/services/patient';

interface Iprops {
    isShowImportPatientModal: (show: boolean) => void;
    importPatient: boolean;
    actionRef: React.MutableRefObject<ActionType | undefined>;
}

const ImportPatient = (props: Iprops) => {
    const { isShowImportPatientModal, importPatient, actionRef } = props
    // 存储上传成功状态
    const [flag, setFlag] = useState(false)
    // 存储上传成功条数
    const [success_count, setSuccess_count] = useState(0)
    // 存储上传失败条数
    const [failed_count, setFailed_count] = useState(0)
    // 存储上传失败数据
    const [failed_data, setFailed_data] = useState([])
    // 控制loading状态
    const [isShowLoading, setIsShowLoading] = useState(false)


    // 解析上传的excel文件 读取数据
    const analyseExcelToJson = (file: any) => {
        return new Promise((resolve, reject) => {
            // console.log(file);
            if (file.originFileObj instanceof File) {
                const reader = new FileReader();
                reader.onloadend = (progressEvent: any) => {
                    const data = new Uint8Array(progressEvent.target.result);
                    const options: any = { type: 'array' };
                    const workbook = read(data, options);
                    const sheetName: any = workbook.SheetNames;
                    const sheet = workbook.Sheets[sheetName[0]];
                    const jsonData = utils.sheet_to_json(sheet, { header: 1, defval: '', blankrows: false })
                    resolve(jsonData);
                };
                reader.readAsArrayBuffer(file.originFileObj);
            } else {
                reject(new Error('入参不是 File 类型'));
            }
        });
    };
    //批量导入
    const uploadprops = {
        name: 'file',
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        showUploadList: false,
        onChange(info: any) {
            if (info.file.status !== 'uploading') {
                setIsShowLoading(true)
                setFlag(false)
                analyseExcelToJson(info.file).then(async (result: any) => {
                    // console.log('表格数据', result.slice(1))
                    let res: any = [];
                    const newArr = result.slice(1)
                    const newPhoneListLength = new Set(newArr.map((item: any) => item[0])).size;
                    const newIdCardListLength = new Set(newArr.map((item: any) => item[2])).size;
                    // console.log('newPhoneListLength', newPhoneListLength);
                    // console.log('newIdCardListLength', newIdCardListLength);
                    //判断 result 中 必填字段是否为空
                    if (newArr.some((item: any) => item[0].toString().trim() === '' || item[1].toString().trim() === '' || item[2].toString().trim() === '')) {
                        message.error('上传失败，表格内有必填项为空！')
                        setIsShowLoading(false)
                        return;
                    }
                    //判断 result 中 是否有重复手机号
                    //判断 result 中 是否有重复身份证号
                    if (newArr.length != newPhoneListLength || newArr.length != newIdCardListLength) {
                        message.error('上传失败，表格内数据有手机号或身份证号重复！')
                        setIsShowLoading(false)
                        return;
                    }
                    newArr.map((item: any) => res.push({ 'phone': item[0], 'name': item[1], 'id_card': item[2], 'address': item[3], 'doctor': item[4].toString(), 'before_illness': item[5] }))
                    let params: any = await import_patient_list({ patient_list: JSON.stringify(res) })
                    if (params.code == 200) {
                        message.success('上传成功！')
                        setIsShowLoading(false)
                        // 刷新外侧列表
                        actionRef.current?.reload()
                        setFlag(true)
                        setSuccess_count(params.data.success_count)
                        setFailed_count(params.data.failed_count)
                        setFailed_data(params.data.failed)
                    } else {
                        message.error(params.msg)
                        setIsShowLoading(false)
                    }
                });
            }
        }
    };

    // 下载上传失败数据
    const downloadFailedData = (tableName: string = '上传失败数据') => {
        // 存储表格数据
        let tableData: any = [];
        // 添加标题行
        let title = ['手机号', '姓名', '身份证号', '地址', '结对医生', '病史', '失败原因'];
        failed_data.map((item: { phone: string; name: string; id_card: string; address: string; doctor: string; before_illness: string; failed_reason: string }) => {
            let objRow = {
                '手机号': item.phone,
                '姓名': item.name,
                '身份证号': item.id_card,
                '地址': item.address,
                '结对医生': item.doctor,
                '病史': item.before_illness,
                '失败原因': item.failed_reason
            }
            tableData.push(objRow)
        })

        var option = {
            fileName: tableName,
            datas: [
                {
                    sheetHeader: title,//表头数据
                    sheetData: tableData,//数据源
                    sheetName: 'sheet',
                    sheetFilter: title,
                    columnWidths: ['5', '5', '10', '10', '5', '5', '12']
                }
            ]
        };
        let toExcel = new ExportJsonExcel(option);
        toExcel.saveExcel();
    }
    return (
        <Modal
            title="导入患者"
            open={importPatient}
            onCancel={() => isShowImportPatientModal(false)}
            width={500}
            destroyOnClose={true}
            footer={null}
        >
            <Divider />
            <div style={{ cursor: 'pointer' }} onClick={() => download('https://lmn-broadcast.oss-cn-hangzhou.aliyuncs.com/manage_import_patient.xlsx', '患者信息模板', '')}>1、下载<span style={{ color: '#1677FF' }}>《患者信息模板》</span>，批量导入患者信息</div>
            <div style={{ marginTop: '20px', display: 'flex', alignItems: 'center', }}>2、上传填写好的患者信息模板 <div style={{ margin: '0 10px 0 10px' }}><Upload {...uploadprops}>
                <Button>上传</Button>
            </Upload></div> {isShowLoading ? <Spin indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />} /> : ''}</div>
            {flag ? <div style={{ marginTop: "20px", display: 'flex' }}>导入结果：成功导入{success_count}条数据，{failed_count}条失败 {failed_count > 0 ? <div style={{ color: '#1677FF', cursor: 'pointer', marginLeft: '20px' }} onClick={() => downloadFailedData()}>下载失败数据</div> : ""}</div> : ""}
        </Modal>
    )
}
export default ImportPatient;